package com.solocredit.finance.ui.steps.act

import android.view.View
import androidx.core.graphics.toColorInt
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaStepsBinding
import com.solocredit.finance.databinding.ItemMullaStepTitleBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.market.act.MullaApplyAct
import com.solocredit.finance.ui.steps.fm.MullaStepAccountFm
import com.solocredit.finance.ui.steps.fm.MullaStepCommonFm
import com.solocredit.finance.ui.steps.fm.MullaStepOcrFm
import com.solocredit.finance.ui.steps.fm.MullaStepPhoneBookFm
import com.solocredit.finance.ui.steps.fm.MullaStepSelfieFm
import com.solocredit.finance.ui.steps.impl.MullaStepsPresenterImpl
import com.solocredit.finance.ui.steps.view.IMullaStepsView
import com.solocredit.finance.utils.MullaChoosePhoneBookUtils
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/30 13:53
 * @Annotation：认证流程
 */
class MullaStepsAct: MvpAct<IMullaStepsView, MullaStepsPresenterImpl>(),IMullaStepsView {

    private var _binding: ActMullaStepsBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    //选择联系人
    var pickPhonebook: MullaChoosePhoneBookUtils? = null

    override fun createPresenter(): MullaStepsPresenterImpl {
        return MullaStepsPresenterImpl(this)
    }
    override fun getMullaRootView(): View {
        _binding = ActMullaStepsBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor("#FFF7F5FF".toColorInt())
        setMullaBackBtnRes(R.mipmap.mulla_back_black)
        setMullaRightBtnRes(R.mipmap.mulla_kefu_icon)
        setMullaTextTitle(getString(R.string.steps_title))

        pickPhonebook = MullaChoosePhoneBookUtils(this)
    }

    override fun initMullaListener() {
        rootViewBinding.ivFun.setOnClickListener {
            val eventRemark = presenter.loadMullaCurrentStepTitle()
            showMullaKefuDialog(eventRemark)
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,eventRemark)
        }
        rootViewBinding.ivLanguage.setOnClickListener {
            val eventRemark = presenter.loadMullaCurrentStepTitle()
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,eventRemark)
            showMullaLanguageDialog(eventRemark, onSelectCallback = {
            })
        }
        //联系人提交
        _binding?.btnPhoneBookNext?.setOnClickListener {
            //通知提交联系人数据
            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_STEP_PHONEBOOK_SUBMIT))
        }
        //流程认证完成
        _binding?.btnContinuer?.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_STEP_COMPLETE_CONTINUER)
            //首页点击的产品信息是否存在，存在 -> 进入申贷页，不存在 -> 返回首页
            val pName = MullaConfigs.clickProductName
            val pToken = MullaConfigs.clickProductToken
            //子产品
            if (pName != MullaConfigs.MULLA_APPNAME || pToken.isEmpty()){
                //非主产品，需要复制主产品信息到子产品
                presenter?.onMullaCopyMainProductToChildProductAction(pName)
                return@setOnClickListener
            }
            //主产品 -> 进入申贷页
            showMullaApplyPage()
        }
    }

    override fun initMullaData() {
        presenter.loadMullaProcessStepAction()

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.visibility = View.GONE
        } else {
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.addView(licenseView())
            _binding?.licenseLayout?.visibility = View.VISIBLE
        }
    }

    /**
     * 提交
     */
    fun onMullaSubmitProcessAction(path: String,params: JSONObject){
        showMullaLoading(isTOuchOut = false, isCancel = true)
        presenter.onMullaSubmitProcessAction(path,params)
    }

    /**
     * 设置当前流程进度
     */
    override fun showMullaStepsProgress(max: Int, progress: Int) {
        _binding?.progressBar?.max = max
        _binding?.progressBar?.progress = progress

        //隐藏联系人提交按钮 - 只有到填写联系人才显示
        _binding?.btnPhoneBookNext?.visibility = View.GONE
    }

    /**
     * 移除所有View
     */
    override fun removeMullaStepAllViews() {
        _binding?.selfieTipsLayout?.visibility = View.GONE
        _binding?.afterLayout?.removeAllViews()
        _binding?.afterLayout?.visibility = View.GONE
        _binding?.contentLayout?.removeAllViews()
        _binding?.beforeLayout?.removeAllViews()
        _binding?.beforeLayout?.visibility = View.GONE
        _binding?.btnContinuer?.visibility = View.GONE
    }

    /**
     * 已完成的步骤
     */
    override fun addMullaStepAfterView(stepTitle: String) {
        val itemView = ItemMullaStepTitleBinding.inflate(layoutInflater)
        itemView.textStepTitle.text = stepTitle

        itemView.stepLayout.setBackgroundColor("#FF8027FF".toColorInt())
        itemView.textStepTitle.setTextColor("#FFFFFFFF".toColorInt())
        itemView.imgStepStatus.setImageResource(R.mipmap.mulla_step_after_icon)

        _binding?.afterLayout?.addView(itemView.root)
        _binding?.afterLayout?.visibility = View.VISIBLE
    }

    /**
     * 未开始的步骤
     */
    override fun addMullaStepBeforeView(stepTitle: String) {
        val itemView = ItemMullaStepTitleBinding.inflate(layoutInflater)
        itemView.textStepTitle.text = stepTitle

        itemView.stepLayout.setBackgroundColor("#FFF6F6F6".toColorInt())
        itemView.textStepTitle.setTextColor("#FFE0DBEE".toColorInt())
        itemView.imgStepStatus.setImageResource(R.mipmap.mulla_step_before_icon)

        _binding?.beforeLayout?.addView(itemView.root)
        _binding?.beforeLayout?.visibility = View.VISIBLE
    }

    /**
     * 所有步骤已完成
     */
    override fun showMullaStepsCompletePage() {
        _binding?.btnContinuer?.visibility = View.VISIBLE
    }

    /**
     * 通用样式
     */
    override fun showMullaStepCommonPage(stepItem: JSONObject) {
        val commonFm = MullaStepCommonFm(stepItem)
        replaceContainerFragement(R.id.contentLayout,commonFm)

        //显示提交按钮
        _binding?.btnPhoneBookNext?.visibility = View.VISIBLE
    }

    /**
     * 联系人
     */
    override fun showMullaStepPhoneBookPage(stepItem: JSONObject) {
        val phonebookFm = MullaStepPhoneBookFm(this,stepItem)
        replaceContainerFragement(R.id.contentLayout,phonebookFm)

        //显示联系人提交按钮
        _binding?.btnPhoneBookNext?.visibility = View.VISIBLE
    }

    /**
     * Ocr
     */
    override fun showMullaStepOcrPage(stepItem: JSONObject) {
        val ocrFm = MullaStepOcrFm(stepItem)
        replaceContainerFragement(R.id.contentLayout,ocrFm)

        //证件照，不显示已完成和未开始的步骤
        _binding?.afterLayout?.visibility = View.GONE
        _binding?.beforeLayout?.visibility = View.GONE
    }

    /**
     * 自拍
     */
    override fun showMullaStepSelfiePage(stepItem: JSONObject) {
        //自拍照需要显示顶部提示
        _binding?.selfieTipsLayout?.visibility = View.VISIBLE
        val selfierFm = MullaStepSelfieFm(stepItem)
        replaceContainerFragement(R.id.contentLayout,selfierFm)

        //自拍照，不显示已完成和未开始的步骤
        _binding?.afterLayout?.visibility = View.GONE
        _binding?.beforeLayout?.visibility = View.GONE
    }

    /**
     * 法语地区添加联系人
     */
    override fun showMullaStepAccountPage(stepItem: JSONObject) {
        val accountFm = MullaStepAccountFm(stepItem)
        replaceContainerFragement(R.id.contentLayout,accountFm)

        //显示提交按钮
        _binding?.btnPhoneBookNext?.visibility = View.VISIBLE
    }

    /**
     * 进入申贷页
     */
    override fun showMullaApplyPage() {
        //首页点击的产品信息是否存在，存在 -> 进入申贷页，不存在 -> 返回首页
        val pName = MullaConfigs.clickProductName
        val pToken = MullaConfigs.clickProductToken
        if (pName.isNotEmpty() && pToken.isNotEmpty()){
            MullaApplyAct.start(this,pName,pToken)
        }
        finish()
    }

    /**
     * 流程提交成功
     * 需要发送通知刷新总流程
     */
    override fun showMullaSubmitSuccess() {
        showMullaLoading()
        //通知刷新总流程
        MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PROCESS_REFRESH))
    }

    override fun onMullaEvent(event: MullaEventData) {
        super.onMullaEvent(event)
        if(event.eventType == MullaEventData.TYPE.MULLA_PROCESS_REFRESHED){//总流程刷新完成
            hideMullaLoading()
            presenter.loadMullaProcessStepAction()
        }
    }

    override fun onStop() {
        super.onStop()
        _binding?.root?.clearFocus()
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}